import React, { Component } from 'react';
import { Button, Col, Divider, Drawer, Input, message, Row, Select, Tag, Tooltip } from 'antd';
import TextArea from 'antd/es/input/TextArea';
import { value } from 'lodash/seq';
import { Base64 } from 'js-base64';
// import { ipcRenderer } from 'electron';

// const ipcRenderer = require('electron').ipcRenderer;
// // 这里是接收主进程传递过来的参数，这里的on要对应主进程send过来的名字
// ipcRenderer.on('asynchronous-reply', function(event, arg) {
// // 这里的arg是从主线程请求的数据
//   console.log('render+' + arg);
// });
const path = 'C:\\Users\\Public\\devUtils_scriptLab.json';
// window.electron.ipcRenderer.inputStream('C:\\Users\\zhyu\\Desktop\\StringRespModel.java');
// window.electron.ipcRenderer.outputStream('C:\\Users\\Public\\devUtils_scriptLab.txt', '123');
// window.electron.ipcRenderer.once('inputStream', (arg) => {
//   console.log(arg);
// });
class ScriptWorkbench extends Component {

  constructor(props) {
    super(props);
    this.confirm = this.confirm.bind(this);
    this.onClose = this.onClose.bind(this);
    this.showDrawer = this.showDrawer.bind(this);
    this.save = this.save.bind(this);
    this.showTags = this.showTags.bind(this);
    this.showTag = this.showTag.bind(this);
    this.closeTag = this.closeTag.bind(this);
    this.clickTag = this.clickTag.bind(this);
    this.saveHistory = this.saveHistory.bind(this);
    this.changeScriptType = this.changeScriptType.bind(this);
    this.state = {
      value: null,
      loadings: [],
      result: '',
      script: null,
      scriptName: null,
      scriptType: null,
      visible: false,
      data: {},
      scriptTypeMessage: null
    };
    window.electron.ipcRenderer.once('inputStream', (arg) => {
      console.log('输入流收到消息: %s', arg);
      if (arg == '读取失败') {
        message.warn('没有读取到保存文档, 开始新建文档');
        let data = {
          date: new Date(),
          softwareVersion: 1.0,
          history: []
        };
        window.electron.ipcRenderer.outputStream(path, JSON.stringify(data, null, 4));
      } else {
        let data = JSON.parse(arg);
        this.setState({ data: data });
      }
    });
    window.electron.ipcRenderer.once('outputStream', (arg) => {
      console.log('输出流收到消息: %s', arg);
      message.destroy();
      message.info(arg);
    });
  }

  saveHistory() {
    window.electron.ipcRenderer.outputStream(path, JSON.stringify(this.state.data, null, 4));
  }

  changeScriptType(val){
    let scriptTypeMessage = null;
    switch (val){
      case '字符串模式':
        scriptTypeMessage = '变量：str';
        break;
      case '数组模式':
        scriptTypeMessage = '变量：arr';
        break;
      case '元素模式':
        scriptTypeMessage = '变量：e';
        break;
    }
    this.setState({ scriptType: val, scriptTypeMessage: scriptTypeMessage});
  }

  closeTag(e, index) {
    e.preventDefault();
    let data = this.state.data;
    let his = data.history;
    console.log('索引:%i, 数据: %o', index, his);
    his.splice(index, 1);
    let newData = { ...data, history: his };
    console.log('索引:%i, 数据: %o', index, his);
    this.setState({ data: newData });
  }

  clickTag(index) {
    let his = this.state.data.history[index];
    if (!!his) {
      let script = Base64.decode(his.script);
      let scriptType = his.scriptType;
      let scriptName = his.scriptName;
      this.setState({
        script: script,
        scriptType: scriptType,
        scriptName: scriptName
      });
      this.changeScriptType(scriptType);
    }
  }

  showTag(obj, index) {
    let scriptType = obj.scriptType;
    let post = null;
    switch (scriptType) {
      case '字符串模式':
        post = 's';
        break;
      case '数组模式':
        post = 'a';
        break;
      case '元素模式':
        post = 'e';
        break;
    }
    return <Tag
      key={index}
      className='edit-tag'
      closable={true}
      onClick={() => this.clickTag(index)}
      index={index}
      onClose={(e) => this.closeTag(e, index)}
    >{obj.scriptName + '[' + post + ']'}</Tag>;
  }

  showTags() {
    let tags = [];
    let his = this.state.data.history;
    if (!!his) {
      let index = 0;
      for (let item of his) {
        tags.push(this.showTag(item, index++));
      }
    }
    return tags;
  }

  save() {
    let script = this.state.script;
    let scriptType = this.state.scriptType;
    let scriptName = this.state.scriptName;
    if (null === scriptType || (!scriptName)) {
      message.error('请填写完全部信息');
      return;
    }
    if (!script || script.trim().length == 0) {
      message.error('请填写脚本');
      return;
    }
    let history = this.state.data.history;
    if (undefined === history) {
      history = [];
    }
    let item = { scriptName: scriptName, scriptType: scriptType, script: Base64.encode(script) };
    if (history.length > 0) {
      let find = false;
      for (let his of history) {
        if (his.scriptName == item.scriptName) {
          his.script = item.script;
          his.scriptType = item.scriptType;
          find = true;
          break;
        }
      }
      if (!find) {
        history.push(item);
      }
    } else {
      history.push(item);
    }
    let data = {
      date: new Date(),
      softwareVersion: 1.0,
      history: history
    };
    this.setState({ data: data });
    window.electron.ipcRenderer.outputStream(path, JSON.stringify(data, null, 4));
  }

  confirm() {
    if (!this.state.script) {
      message.warn('请先选择脚本');
      return;
    }
    let str = this.state.value;
    if (!str) {
      message.warn('请输入数据');
      return;
    }
    if (str.trim().length == 0) {
      message.warn('请输入数据');
      return;
    }
    let type = this.state.scriptType;
    let finalScript = null;
    let script = this.state.script;
    let result = '';
    let env = {};
    try {
      switch (type) {
        case '字符串模式':
          env.str = str;
          finalScript = 'let str = env.str;try{' + script + '}catch(e){console.log(e);} env.str = str; return env;';
        {
          const cmd = new Function('env', finalScript);
          env = cmd(env);
          result = env.str;
        }
          break;
        case '数组模式':
          env.arr = str.split('\n');
          finalScript = 'let arr = env.arr;try{' + script + '}catch(e){console.log(e);} env.arr = arr; return env;';
        {
          const cmd = new Function('env', finalScript);
          let arr = cmd(env).arr;
          for (let i = 0; i < arr.length; i++) {
            if (null != arr[i]) {
              result += arr[i] + '\n';
            }
          }
        }
          break;
        case '元素模式':
          let arr = str.split('\n');
          for (let i = 0; i < arr.length; i++) {
            env.e = arr[i];
            finalScript = 'let e = env.e;try{' + script + '}catch(e){console.log(e);} env.e = e; return env;';
            {
              const cmd = new Function('env', finalScript);
              let e = cmd(env).e;
              result += e + '\n';
            }
          }
          break;
        default:
          message.warn('请选择正确的类型');
          return;
      }
    } catch (e) {
      console.log(e);
    }
    console.log('执行类型: %s, 执行脚本: %s,', type, script);
    this.setState({ result: result });
  }

  onClose() {
    this.setState({
      visible: false
    });
  }

  showDrawer() {
    window.electron.ipcRenderer.inputStream(path);
    this.setState({
      visible: true
    });
  }


  render() {
    return (
      <div>
        <Tooltip placement='top' title={'双击清除内容'}>
          <Row gutter={24}>
            <Col span={8}><span>{this.state.scriptName}</span></Col>
            <Col span={8}><span>{this.state.scriptType}</span></Col>
          </Row>
          <TextArea
            value={this.state.value}
            onChange={({ target: { value } }) => {
              this.setState({ value: value });
            }}
            onDoubleClick={() => this.setState({ value: '' })}
            placeholder='请输入待处理的数据'
            autoSize={{ minRows: 10, maxRows: 10 }}
          />
        </Tooltip>

        <div style={{ textAlign: 'center' }}>
          <Button type='primary' style={{ margin: '2px' }}
                  loading={this.state.loadings[0]} onClick={this.showDrawer}>
            脚本
          </Button>
          <Button type='primary' style={{ margin: '2px' }}
                  loading={this.state.loadings[0]} onClick={this.confirm}>
            提交
          </Button>
          <Button type='primary' style={{ margin: '2px' }} data-clipboard-text={this.state.result} className={'copy'}>
            复制
          </Button>
        </div>
        <TextArea
          value={this.state.result}
          placeholder='格式化后的字符串'
          autoSize={{ minRows: 15, maxRows: 15 }}
        />
        <Drawer
          title='脚本'
          placement='right'
          closable={false}
          onClose={this.onClose}
          visible={this.state.visible}
          getContainer={false}
          style={{ position: 'absolute' }}
          width='50%'
          mask='false'
        >
          <span style={{ fontSize: '10px', color: 'red' }}>脚本内容保存在C:\Users\Public\devUtils\scriptLab.txt</span><br />
          <Input value={this.state.scriptName} addonBefore={'名字'}
                 style={{ margin: 10, width: 300 }}
                 size={'small'}
                 onChange={({ target: { value } }) => {
                   this.setState({ scriptName: value });
                 }}
                 onDoubleClick={() => this.setState({ scriptName: '' })}
          />
          <Row gutter={24}>
            <Col span={8}>
              <Select dropdownMatchSelectWidth={100} value={this.state.scriptType} placeholder={'请选择'}
                      onChange={val => this.changeScriptType(val)}>
                <Select.Option value={'字符串模式'}>字符串模式</Select.Option>
                <Select.Option value={'数组模式'}>数组模式</Select.Option>
                <Select.Option value={'元素模式'}>元素模式</Select.Option>
              </Select>
            </Col>
            <Col span={8}>{this.state.scriptTypeMessage}</Col>
            <Col span={8}>
              <Button onClick={this.save}>保存当前脚本</Button>
            </Col>
          </Row>
          <TextArea
            value={this.state.script}
            style={{ marginTop: 10 }}
            onChange={({ target: { value } }) => {
              this.setState({ script: value });
            }}
            onDoubleClick={() => this.setState({ script: '' })}
            placeholder='请输入脚本'
            autoSize={{ minRows: 10, maxRows: 10 }}
          />
          <Divider orientation='left'>历史标签</Divider>
          <Divider orientation='right'><Button onClick={this.saveHistory}>保存历史标签</Button></Divider>
          <div>
            {this.showTags()}
          </div>
        </Drawer>
      </div>
    );
  }
}

export default ScriptWorkbench;
